﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OPMS_V1.BOL;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace OPMS_V1.AccessControls
{
    public partial class Login : System.Web.UI.Page
    {
        Register objRegBOL = new Register();
        Crypto crypt = new Crypto();

        /// <summary>
        /// This method is used for the Page Load events that occurs every time when the page Loads.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            lblUsernameError.Visible = false;
            lblRegisterError.Visible = false;
            regexReqUsername.Enabled = false;
            regexReqEmail.Enabled = false;
            regexReqPassword.Enabled = false;
            lblRequired.Visible = false;
            lblLoginError.Visible = false;
            lblEmailExists.Visible = false;
        }

        /// <summary>
        /// This function is used to register the user on the basis of their existance.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        #region Registration Button functioning
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            //Registration details parameters
            Boolean userexist = false;
            Boolean emailexist = false;
            Boolean successful = false;
            string accountName = txtRegAccountName.Text;
            string email = txtRegEmail.Text;
            string password = crypt.Encrypt(txtRegPassword.Text);
            string accountStatus = "Enabled";
            string accountType = "User";
            string IdentificationId = "IDN001";
            string lastLogin = System.Convert.ToString(DateTime.Now);

            if (accountName == "" || txtRegPassword.Text == "" || email == "")
            {
                lblRequired.Visible = true;
            }
            else
            {
                regexReqUsername.Enabled = false;
                regexReqEmail.Enabled = false;
                regexReqPassword.Enabled = false;

                //This is used for getting all the usernames that exists.
                List<String> username = new List<string>();
                username = objRegBOL.getUsernames();

                //This is used for getting all the emailAddress that exists.
                List<String> emailaddress = new List<string>();
                emailaddress = objRegBOL.getEmailAddress();

                //If the Username matches then the username exists (TRY SOME ANOTHER USERNAME)
                foreach (string s in username)
                {
                    if (s.Equals(accountName))
                    {
                        userexist = true;
                    }
                }

                //If the email matches then the username exists (TRY SOME ANOTHER USERNAME)
                foreach (string s in emailaddress)
                {
                    if (s.Equals(email))
                    { emailexist = true;}
                }

                //If username not matches then register the user with the encrypted password stored on to the database
                if (userexist == false && emailexist==false)
                {
                    //Registering the user
                    try
                    {
                        //Registering the Details of the User (AccountName, email, password, accountStatus, accountType, IdentificationId, lastLogin
                        objRegBOL.RegisterUser(accountName, email, password, accountStatus, accountType, IdentificationId, lastLogin);
                        successful = true;
                        Session["user"] = accountName;
                    }
                    //If it fails to Register the User
                    catch (Exception)
                    {
                        lblRegisterError.Visible = true;
                        successful = false;
                    }
                }
                //If the user exists then show that username exists.
                else
                {
                    //If the username exists then show the user exists message
                    if (userexist == true)
                    {
                        lblUsernameError.Visible = true;
                        successful = false;
                    }
                    //If the email exists then show the email exists message
                    if (emailexist == true)
                    {
                        lblEmailExists.Visible = true;
                        successful = false;
                    }
                }
                if (successful == true)
                {
                    if (chkTerms.Checked == true)
                    {
                        Response.Redirect("~//Property.aspx?Mode=buy");
                    }
                    else
                    {
                        lblRegisterError.Visible = true;
                        lblRegisterError.Text = "Please accept the terms and conditions.";
                    }
                }
            }
        }
        #endregion Registration Button functioning

        /// <summary>
        /// This function is used for Logging to the system (Authentication)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        #region Login Button functioning
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //Registration details parameters
            Boolean successful = false;
            string accountName = txtAccountName.Text;
            string password = crypt.Encrypt(txtPassword.Text);
            string lastLogin = System.Convert.ToString(DateTime.Now);

            //If the user enters no data in the fields, show errors
            if (accountName == "" || txtPassword.Text == "" )
            {
                lblLoginError.Visible = true;
            }
            else
            {
                //Trying to validate the user with the Username and encrypted Password stored on to the database
                int response = objRegBOL.ValidateUser(accountName, password);

                if (response == 0)
                {
                    //Maitaing the session for the user logon.
                    successful = true;
                    Session["user"] = accountName;
                }
                else
                {
                    successful = false;
                    lblLoginError.Visible = true;
                }

                if (successful == true)
                {
                    //If admin is the user then redirect to his location
                    if (Session["user"].ToString().Equals("admin"))
                    {
                        Response.Redirect("~//Restricted//Admin//PropertyAds.aspx");
                    }
                    //If its a normal user then redirect to his location
                    else
                    {
                        //If sucessfully authenticate the system redirect to desired page
                        Response.Redirect("~//Property.aspx?Mode=buy");
                    }
                }
            }
        }
        #endregion Login Button functioning

        protected void lnkForgot_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/AccessControls/ForgottenPassword.aspx");
        }
    }
}
